package com.jackson.payparams.utils;

/*
 * Author: JacksonCoder
 * FileName: NotifyBussinessAssess
 * Version: 1.0.0
 * Date: 2025/7/14
 */

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

import com.fasterxml.jackson.databind.ObjectMapper;


public class NotifySignatureValidation {
    public static void main(String[] args) {

        String url = "/v1.0/qr/qr-mpm-notify";   // 动态生成
        String timestamp = "2025-01-18T12:55:00+07:00";
        String method = "POST";

        // 示例 requestBody 是 JSON 数据
        ObjectMapper objectMapper = new ObjectMapper();
        String requestBody = "";
        try {
            // 计算请求体的 SHA-256 哈希
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] requestBodyHash = digest.digest(requestBody.getBytes(StandardCharsets.UTF_8));

            // 拼接数据字符串
            String data = method + ":" + url + ":" + bytesToHex(requestBodyHash) + ":" + timestamp;

            // Base64 解码签名
            String headerSign = "YOU SIGNATURE FOR REAL"; // 替换为实际签名
            byte[] signature = Base64.getDecoder().decode(headerSign);

            // 解析公钥
            String publicKeyPEM = "-----BEGIN PUBLIC KEY-----\n" +
                    "YOU PUBLICKEYPEM" +
                    "-----END PUBLIC KEY-----\n";
            publicKeyPEM = publicKeyPEM.replace("-----BEGIN PUBLIC KEY-----", "")
                    .replace("-----END PUBLIC KEY-----", "")
                    .replaceAll("\\s", "");
            byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyPEM);
            X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyBytes);
            PublicKey publicKey = java.security.KeyFactory.getInstance("RSA").generatePublic(spec);

            // 验证签名
            Signature sig = Signature.getInstance("SHA256withRSA");
            sig.initVerify(publicKey);
            sig.update(data.getBytes());  // StandardCharsets.UTF_8
            boolean isValid = sig.verify(signature);

            if (isValid) {
                System.out.println("Signature is valid");
            } else {
                System.out.println("Signature is invalid");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 工具方法：将字节数组转换为十六进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}
